package com.marvhong.videoeditor.addtext.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.marvhong.videoeditor.R;
import com.marvhong.videoeditor.VideoEditFun;
import com.marvhong.videoeditor.addtext.base.LibVideoBaseAddTextActivity;
import com.marvhong.videoeditor.addtext.imgsdk.IMGTextEditDialog;
import com.marvhong.videoeditor.addtext.imgsdk.core.IMGText;
import com.marvhong.videoeditor.addtext.utils.LibVideoEditViewUtils;
import com.marvhong.videoeditor.addtext.widget.AddTxtIMGView;
import com.marvhong.videoeditor.addtext.widget.AddTxtVideoCusLinear;
import com.marvhong.videoeditor.addtext.widget.AddTxtVideoView;
import com.marvhong.videoeditor.dialog.NormalProgressDialog;
import com.north.light.librxffmpeg.FFmpegFunCallback;
import com.north.light.librxffmpeg.FFmpegFunc;

import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 视频添加文字页面
 */
public class VideoAddTextActivity extends LibVideoBaseAddTextActivity {
    /**
     * request result params
     */
    private static final String STR_PATH_ORG = "STR_PATH_ORG";
    public static final int VIDEO_ADD_TEXT_REQ = 0x003;
    public static final int VIDEO_ADD_TEXT_RES = 0x004;

    //view
    private LinearLayout mPlayerRoot;
    private AddTxtVideoView mPlayView;
    private AddTxtVideoCusLinear mTextRoot;
    private AddTxtIMGView mAddTextParent;

    //取消and完成
    private TextView mCancelTV;
    private TextView mConfirmTV;

    //视频传入路径
    private String mVideoPath;
    //视频宽高
    private long mVideoWidth = 0L;
    private long mVideoHeight = 0L;

    //文字输入弹窗
    private IMGTextEditDialog mTextDialog;
    //是否增加过文字标识
    private AtomicBoolean mAddTextTAG = new AtomicBoolean(false);
    //是否处理视频中的标识
    private boolean mIsDealingVideo = false;

    public static void launch(Activity context, String videoPath) {
        Intent intent = new Intent(context, VideoAddTextActivity.class);
        intent.putExtra(STR_PATH_ORG, videoPath);
        context.startActivityForResult(intent, VIDEO_ADD_TEXT_REQ);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mVideoPath = getIntent().getStringExtra(STR_PATH_ORG);
        if (TextUtils.isEmpty(mVideoPath)) {
            shortToast("传入视频路径错误");
            finish();
            return;
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.lib_video_eidt_activity_video_add_text;
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPause();
    }

    private void videoPlay() {
        try {
            if (mPlayView != null) {
                mPlayView.start();
            }
        } catch (Exception e) {

        }
    }

    private void videoPause() {
        try {
            if (mPlayView != null) {
                mPlayView.pause();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 初始化video view
     */
    private void initVideoView() {
        //动态把video view添加到布局里面
        try {
            mAddTextParent = findViewById(R.id.video_add_text_font_edittx);
            mPlayView = new AddTxtVideoView(getApplicationContext());
            mPlayerRoot.addView(mPlayView);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mPlayView.getLayoutParams();
            params.width = LinearLayout.LayoutParams.MATCH_PARENT;
            params.height = LinearLayout.LayoutParams.MATCH_PARENT;
            mPlayView.setLayoutParams(params);
            MediaController mediaController = new MediaController(this);
            mediaController.setVisibility(View.INVISIBLE);
            mPlayView.setMediaController(mediaController);
            mPlayView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    return true;
                }
            });
            mPlayView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    videoPlay();
                }
            });
            //得到视频的宽高----------------------------------------------------
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(mVideoPath);
            long width = Long.parseLong(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
            long height = Long.parseLong(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
            String orientation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
            if ("90".equals(orientation)) {
                mVideoWidth = Math.min(width, height);
                mVideoHeight = Math.max(width, height);
            } else {
                mVideoWidth = width;
                mVideoHeight = height;
            }
            retriever.release();
            //初始化回执控件的宽高----------------------------------------------------
            mTextRoot.postDelayed(new Runnable() {
                @Override
                public void run() {
                    float cacheWidth = mPlayView.getMeasuredWidth();
                    float cacheHeight = mPlayView.getMeasuredHeight();
                    //设置文本布局的宽高和视频大小布局对应------------------
                    //对比视频宽高，对应控件做出放大
                    float widthRate = cacheWidth / mVideoWidth;
                    float heightRate = cacheHeight / mVideoHeight;
                    int trueWidth = (int) (mVideoWidth * widthRate);
                    int trueHeight = (int) (mVideoHeight * heightRate);
                    ViewGroup.LayoutParams layoutParams1 = mTextRoot.getLayoutParams();
                    layoutParams1.width = trueWidth;
                    layoutParams1.height = trueHeight;
                    mTextRoot.setLayoutParams(layoutParams1);
                }
            }, 800);
            mPlayView.setVideoPath(mVideoPath);
        } catch (Exception e) {

        }
    }

    /**
     * 释放video view
     */
    private void releaseVideoView() {
        try {
            mPlayView.stopPlayback();
            mPlayView.suspend();
            mPlayView.setOnErrorListener(null);
            mPlayView.setOnPreparedListener(null);
            mPlayView.setOnCompletionListener(null);
            mPlayView.setMediaController(null);
            mPlayView = null;
            mPlayerRoot.removeAllViews();
        } catch (Exception e) {

        }
    }

    @Override
    protected void initView() {
        super.initView();
        mCancelTV = findViewById(R.id.add_text_cancel);
        mConfirmTV = findViewById(R.id.add_text_confirm);
        mPlayerRoot = findViewById(R.id.video_add_text_content);
        mTextRoot = findViewById(R.id.video_add_text_font_root);
        mTextDialog = new IMGTextEditDialog(VideoAddTextActivity.this,
                new IMGTextEditDialog.Callback() {
                    @Override
                    public void onText(IMGText text) {
                        Log.e("add text", "onText：" + text);
                        //处理输入的文字
                        dealInputFont(text);
                    }
                },
                new IMGTextEditDialog.CancelCallBack() {
                    @Override
                    public void autoCancel() {
                        //用户手动取消监听
                        mCancelTV.performClick();
                    }
                });
        initVideoView();
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        mCancelTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                finish();
            }
        });
        mConfirmTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //完成
                addTextToVideo();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        //显示文字输入弹窗
        if (mTextDialog != null) {
            mTextDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        if (mTextDialog != null) {
            mTextDialog.release();
        }
        NormalProgressDialog.stopLoading();
        FFmpegFunc.getInstance().release();
        releaseVideoView();
        super.onDestroy();
    }


    //function-----------------------------------------------------------------------------------

    /**
     * 开始添加水印到视频里
     */
    private void addTextToVideo() {
        if (!mAddTextTAG.get()) {
            //没有添加过文字--直接结束页面--不设置返回值
            mCancelTV.performClick();
            return;
        }
        if(mIsDealingVideo){
            return;
        }
        mIsDealingVideo = true;
        //至此，编辑过文字，需要合成
        //暂停播放
        videoPause();
        //弹出loading
        NormalProgressDialog.showLoading(this, getResources().getString(R.string.in_process), false);
        LibVideoEditViewUtils.viewSnapshot(mTextRoot, new LibVideoEditViewUtils.ViewSnapListener() {
            @Override
            public void success(Bitmap bitmap) {
                //保存
                try {
                    //开始合成
                    //缩放图片------------------------
                    Matrix matrix = new Matrix();
                    float widthScaleRate = (mVideoWidth * 1f) / (bitmap.getWidth() * 1f);
                    float heightScaleRate = (mVideoHeight * 1f) / (bitmap.getHeight() * 1f);
                    matrix.postScale(widthScaleRate, heightScaleRate);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                    String picDir = getExternalCacheDir().getPath() + "/addtext/cover/" + System.currentTimeMillis() + ".png";
                    String savePicPath = LibVideoEditViewUtils.saveBitmap(bitmap, picDir);
                    if (TextUtils.isEmpty(savePicPath) || !new File(savePicPath).exists()) {
                        return;
                    }
                    //目标mp4文件命名
                    String targetName = getExternalCacheDir().getPath() + "/addtext/video/" + System.currentTimeMillis() + ".mp4";
                    FFmpegFunc.getInstance().addTxt(mVideoPath, savePicPath, targetName, new FFmpegFunCallback() {
                        @Override
                        public void failed(String message) {
                            Log.e("add text", "failed：" + message);
                            NormalProgressDialog.stopLoading();
                            mIsDealingVideo = false;
                        }

                        @Override
                        public void success(String path) {
                            Log.e("add text", "success：" + path);
                            NormalProgressDialog.stopLoading();
                            VideoEditFun.getInstance().notifyAddTextResult(path);
                            finish();
                            mIsDealingVideo = false;
                        }

                        @Override
                        public void cancel() {
                            Log.e("add text", "cancel：");
                            NormalProgressDialog.stopLoading();
                            mIsDealingVideo = false;
                        }
                    });
                } catch (Exception e) {
                    shortToast("合成失败：" + e.getMessage());
                    NormalProgressDialog.stopLoading();
                    mIsDealingVideo = false;
                }
            }

            @Override
            public void failed() {
                shortToast("无法获取文字信息");
                mIsDealingVideo = false;
                NormalProgressDialog.stopLoading();
            }
        });
    }

    /**
     * 处理输入的文字
     */
    private void dealInputFont(IMGText text) {
        String inputContent = text.getText();
        int inputColor = text.getColor();
        if (TextUtils.isEmpty(inputContent)) {
            //没有输入过文字
            return;
        }
        //输入过文字
        mAddTextTAG.set(true);
        //回显到自定义的文字控件里面
        mAddTextParent.addStickerText(text);
    }

}